package com.fqgame.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fqgame.user.entity.UserOrder;
import com.fqgame.user.mapper.UserOrderMapper;
import com.fqgame.user.service.UserOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * 用户订单服务实现类
 */
@Slf4j
@Service
public class UserOrderServiceImpl extends ServiceImpl<UserOrderMapper, UserOrder> implements UserOrderService {

    /**
     * 创建订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOrder(Long userId, Long productId, String productName, BigDecimal amount) {
        log.info("创建订单，用户ID：{}，商品ID：{}，金额：{}", userId, productId, amount);
        
        UserOrder order = new UserOrder();
        order.setOrderNo(generateOrderNo());
        order.setUserId(userId);
        order.setProductId(productId);
        order.setProductName(productName);
        order.setAmount(amount);
        order.setStatus(0); // 待支付
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        // 保存订单
        boolean success = this.save(order);
        if (!success) {
            throw new RuntimeException("创建订单失败");
        }
        
        log.info("订单创建成功，订单ID：{}", order.getId());
        return order.getId();
    }

    /**
     * 支付订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(Long orderId) {
        log.info("支付订单，订单ID：{}", orderId);
        
        UserOrder order = this.getById(orderId);
        if (order == null) {
            log.error("订单不存在，订单ID：{}", orderId);
            return false;
        }
        
        if (order.getStatus() != 0) {
            log.error("订单状态不正确，订单ID：{}，状态：{}", orderId, order.getStatus());
            return false;
        }
        
        // 更新订单状态
        order.setStatus(1); // 已支付
        order.setPayTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        boolean success = this.updateById(order);
        if (success) {
            log.info("订单支付成功，订单ID：{}", orderId);
        } else {
            log.error("订单支付失败，订单ID：{}", orderId);
        }
        
        return success;
    }

    /**
     * 取消超时未支付订单（任务调度示例）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelTimeoutOrders() {
        log.info("开始取消超时未支付订单，时间：{}", LocalDateTime.now());
        
        // 查询30分钟前创建且未支付的订单
        LocalDateTime timeoutTime = LocalDateTime.now().minusMinutes(30);
        
        LambdaQueryWrapper<UserOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserOrder::getStatus, 0) // 待支付状态
                .lt(UserOrder::getCreateTime, timeoutTime); // 创建时间小于超时时间
        
        List<UserOrder> timeoutOrders = this.list(queryWrapper);
        log.info("找到{}个超时未支付订单", timeoutOrders.size());
        
        for (UserOrder order : timeoutOrders) {
            order.setStatus(2); // 已取消
            order.setUpdateTime(LocalDateTime.now());
            boolean success = this.updateById(order);
            
            if (success) {
                log.info("订单已取消，订单ID：{}", order.getId());
            } else {
                log.error("订单取消失败，订单ID：{}", order.getId());
            }
        }
        
        log.info("超时订单取消完成");
    }

    /**
     * 生成订单编号
     */
    private String generateOrderNo() {
        // 简单实现，实际可能需要更复杂的生成逻辑
        return System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8);
    }
}